package com.feelingj.spring.boot.blog.controller;

import java.io.File;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import com.feelingj.spring.boot.blog.util.DirectoryImageUtils;
import com.feelingj.spring.boot.blog.util.FtpUtil;

@Controller
public class FileController {
	
	@Value("${ftp.servce.address}")
	private String ftpip;
	
	@Value("${ftp.servce.port}")
	private Integer ftpport;
	
	@Value("${ftp.servce.user}")
	private String ftpuser;
	
	@Value("${ftp.servce.password}")
	private String ftppassword;
	
	@Value("${ftp.servce.baseurl}")
	private String ftpbaseurl;
	
	@Value("${ftp.url}")
	private String ftpurl;
	
	@PostMapping("/upload")
	public ResponseEntity<String> handleFileUpload(MultipartFile file) {
		File returnFile = null;
		try {
			if (null == file || file.isEmpty()) {
				return ResponseEntity.ok().body("图片不能为空");
			}
			//取文件扩展名
			String originalFilename = file.getOriginalFilename().lastIndexOf(".") ==-1? file.getOriginalFilename()+".jpg":file.getOriginalFilename();
			String ext = (originalFilename.substring(originalFilename.lastIndexOf(".")));
			//生成新文件名
			//可以使用uuid生成新文件名。
			//UUID.randomUUID()
			//可以是时间+随机数生成文件名
			String imageName = DirectoryImageUtils.genImageName();
			//把图片上传到ftp服务器（图片服务器）
			//需要把ftp的参数配置到配置文件中
			//文件在服务器的存放路径，应该使用日期分隔的目录结构
			DateTime dateTime = new DateTime();
			String filePath = dateTime.toString("/yyyy/MM/dd");
			try {
				boolean uploadFile = FtpUtil.uploadFile(ftpip, ftpport, ftpuser, ftppassword, 
						ftpbaseurl, filePath, imageName + ext, file.getInputStream());
			} catch (Exception e) {
				e.printStackTrace();
				return ResponseEntity.ok().body(e.getMessage());
			} 
			return ResponseEntity.status(HttpStatus.OK).body(ftpurl+filePath+"/"+imageName+ext);
		} catch (Exception ex) {
			ex.printStackTrace();
			return ResponseEntity.ok().body(ex.getMessage());
		}
	}
	
}
